package com.j2boot.concurrence;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 解决经典案例中的其中一种方法
 * @author yichengxian
 */
public class SafeConcurrence {


    static int i = 0;


    /**
     * main 方法
     **/
    public static void main(String[] str){
        //创建10个线程
        for(int k = 0; k<10;k ++) new Thread(()->{incNum();}).start();
        System.out.println(i);
    }

    //减少锁的使用
    public static void incNum(){
        //临时变量
        int temp = 0;
        for (int j = 0; j < 100000; j++) {
            temp++;
        }
        ReentrantLock reentrantLock = new ReentrantLock();

        reentrantLock.lock();

        try {

            i = temp;
        }finally {
            reentrantLock.unlock();
        }


    }
}
